// 商品分类
import { findHeadCategory } from '@/api/Home/calt'
// 提供默认的分类数据，防止出现空白的分类效果
import { category } from '@/utils/constant.js'

export default {
  namespaced: true,
  state: {
    // list: ''
    list: category.map((item, index) => ({ id: index, name: item })),
    cartgoods: []
  },
  mutations: {
    // 更新分类列表数据
    updateCate (state, payload) {
      state.list = payload
    },
    setcart (state, cartgoods) {
      console.log(cartgoods.a)

      const zhuangtai = state.cartgoods.findIndex(itme => {
        return itme.id === cartgoods.id
      })
      if (zhuangtai === -1) {
        state.cartgoods.push(cartgoods)
        state.cartgoods[0].shuliang = cartgoods.a
      } else {
        console.log('youxiangt', cartgoods.a, state.cartgoods[zhuangtai].shuliang)
        state.cartgoods[zhuangtai].shuliang = state.cartgoods[zhuangtai].shuliang + cartgoods.a
      }
      console.log(zhuangtai)
    },
    removecart (state, ind) {
      if (state.cartgoods[ind].shuliang <= 1) {
        state.cartgoods.splice(ind, 1)
        return
      }
      state.cartgoods[ind].shuliang--
      console.log(state.cartgoods)
    },
    updateStatus (state, payload) {
      // 修改分类的状态

      const cate = state.list.find(item => item.id === payload.id)

      if (cate) {
        cate.open = payload.open
      }
    }
  },
  actions: {
    // 调用接口获取分类的数据

    async findHeadCategory (context) {
      const ret = await findHeadCategory()
      if (ret && ret.result) {
        ret.result.forEach(item => {
          item.open = false
        })
        context.commit('updateCate', ret.result)
      }
    }
  },
  getters: {
    cateList (state) {
      return state.list.map((item) => {
        return {
          ...item,
          children: item.children && item.children.filter((obj, i) => i < 2)
        }
      })
    }
  }
}
